<?php
namespace app\know\validate;

use app\know\model\SentenceModel;
use think\Validate;
use think\facade\Log;

class SentenceValidate extends Validate
{
    protected $rule = [
        'content' => 'require|min:1|checkContent',
        'id' => 'require|gt:0',
    ];

    protected $message = [
        'content.require' => '内容为必填项',
        'content.min' => '内容不能为空',
        'id.require' => 'id不能为空',
    ];

    protected $scene = [
        'add'  => ['content'],
        'edit' => ['id', 'content'],
        'delete' => ['id'],
    ];

    protected function checkContent($value, $rule, $data)
    {
        if ($this->currentScene == 'edit') 
        {
            return $this->checkContentRepeat($value, $rule, $data);
        }
		else if ($this->currentScene == 'add') 
        {
            return $this->checkName($value, $rule, $data);
        }
		return true;
    }
	
    protected function checkContentRepeat($value, $rule, $data)
    {
        $model = new SentenceModel();
        $item  = $model->where('id', '<>', $data['id'])
                        ->where('content', $data['content'])
                        ->find();

        if (empty($item)) 
        {
            return true;
        } 
        else 
        {
            return $data['content'] . "---编辑-已经存在---";
        }
    }

    protected function checkName($value, $rule, $data)
    {
        $model = new SentenceModel();
        $item  = $model->where('content', $data['content'])
                       ->find();

        if (empty($item)) 
        {
            return true;
        } 
        else 
        {
            return $data['content'] . "---添加-已经存在---";
        }
    }
}